package com.kc.stand.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kc.stand.domain.Article;
import com.kc.stand.domain.FileManage;
import com.kc.stand.domain.Stand;
import com.kc.stand.service.ArticleService;
import com.kc.stand.service.FileManageService;
import com.kc.stand.service.StandService;
import com.kc.stand.vo.StandVo;
import com.kc.sys.common.DataGridView;
import com.kc.sys.common.R;
import com.kc.sys.common.TreeNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author forever_love
 * 编制规则
 * @create 2019--12--20 11:02
 **/
@RestController
@RequestMapping("standFile")
public class StandFileController {

    @Autowired
    private StandService standService;
    @Autowired
    private  FileManageService fileManageService;
    @Autowired
    private ArticleService articleService;
    /**
     *加载编制规则左边的编制树结构Json
     */
    @RequestMapping("loadStandManagerLeftJson")
    public DataGridView loadStandManagerLeftJson(StandVo standVo){
        List<Stand> list = standService.list();
        List<TreeNode> treeNodes = new ArrayList<>();
        for (Stand stand : list) {
            Boolean spread = stand.getOpen()==1?true:false;
            treeNodes.add(new TreeNode(stand.getId(),stand.getPid(),stand.getTitle(),spread));

        }
        return new DataGridView(treeNodes);
    }

    @RequestMapping("loadAllStand")
    public DataGridView loadAllStand(StandVo standVo){

        //获取用户session
        //User user = (User)WebUtils.getSession().getAttribute("user");
        IPage<Stand> page = new Page<>(standVo.getPage(),standVo.getLimit());
        QueryWrapper<Stand> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(standVo.getTitle()),"title",standVo.getTitle());
        queryWrapper.like(StringUtils.isNotBlank(standVo.getAddress()),"address",standVo.getAddress());
        queryWrapper.like(StringUtils.isNotBlank(standVo.getRemark()),"remark",standVo.getRemark());
        queryWrapper.eq(standVo.getId()!=null,"id",standVo.getId()).or().eq(standVo.getId()!=null,"pid",standVo.getId());
        queryWrapper.orderByAsc("ordernum");
        standService.page(page,queryWrapper);
        return new DataGridView(page.getTotal(),page.getRecords());
    }

    //加载最大的排序码
    @RequestMapping("loadStandMaxOrderNum")
    public Map<String ,Object> loadStandMaxOrderNum(){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Stand> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("ordernum");
        List<Stand> list = standService.list(queryWrapper);
        if(list.size()>0){
            map.put("value",list.get(0).getOrdernum()+1);
        }else{
            map.put("value",1);
        }
        return map;
    }

    //添加站细编规
    @RequestMapping("addStand")
    public R addStand(HttpServletRequest request,StandVo standVo){
        String data = request.getParameter("data");
        JSONObject json = JSONObject.parseObject(data);
        Object parentId = json.get("parentId");
        int iparentId = Integer.parseInt(String.valueOf(parentId));
        Object context = json.get("context");
        String scontext = context.toString();
        try {
            standVo.setCreatetime(new Date());
            standVo.setOpen(1);
            standVo.setPid(iparentId);
            standVo.setTitle(scontext);
            standService.save(standVo);
            return R.ok().message("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("添加失败");
        }
    }

    //更新编制
    @RequestMapping("updateStand")
    public R updateStand(HttpServletRequest request,StandVo standVo){
        String data = request.getParameter("data");
        JSONObject json = JSONObject.parseObject(data);
        Object nodeId = json.get("nodeId");
        int inodeId = Integer.parseInt(String.valueOf(nodeId));
        Object editNodeName = json.get("editNodeName");
        String snodeTitle = editNodeName.toString();
        try {
            standVo.setId(inodeId);
            standVo.setTitle(snodeTitle);
            standService.updateById(standVo);
            return R.ok().message("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("更新失败");
        }
    }

    @RequestMapping("updateStandById/{nodeid}")
    public R updateStandById(@PathVariable("nodeid") Integer id, StandVo standVo){
        try {
            standVo.setId(id);
            standService.updateById(standVo);
            return R.ok().message("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("更新失败");
        }
    }
    /**
     * 根据Id 删除
     * */
    @RequestMapping("deleteStand")
    public R deleteById(String  data){
        JSONObject json = JSONObject.parseObject(data);
        Object nodeId = json.get("nodeId");
        int inodeId = Integer.parseInt(String.valueOf(nodeId));
        try {
            standService.removeById(inodeId);
            return R.ok().message("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().message("删除失败");
        }
    }

    //检查当前编制有没有子节点（编制）
    @RequestMapping("checkStandHasChildrenNode")
    public Map<String ,Object> checkStandHasChildrenNode(StandVo standVo){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<Stand> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pid",standVo.getId());
        List<Stand> list = standService.list(queryWrapper);
        if(list.size()>0){
            map.put("value",true);
        }else {
            map.put("value",false);
        }
        return map;
    }
    //根据Id查询详情
    @RequestMapping("findStandTree")
    public R findStandTree(HttpServletRequest request) {
        String nodeId = request.getParameter("nodeId");
        Stand stand = standService.getById(nodeId);
        return R.ok().data("item",stand);
    }
    //根据Id查询编制规则
    @RequestMapping("findStandFileById/{id}")
    public R findStandFileById(@PathVariable("id") Integer id){
        FileManage fileManage = fileManageService.getById(id);
        Stand stand = standService.getById(fileManage.getTreeId());
        return  R.ok().data("item",stand);
    }

    //根据sid查询编制规则
    @RequestMapping("findStandFileById1/{id}")
    public R findStandFileById1(@PathVariable("id") Integer id){
        System.out.println("id-----------------------------------"+id);
        Article article = articleService.getById(id);
        Stand stand = standService.getById(article.getId());
        return  R.ok().data("item",stand);
    }
}
